package com.sample.wanandroidx.widget

import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import android.widget.TextView
import com.sample.wanandroidx.R

open class LinearView : LinearLayout {

    private var _count: Int = 0

    var count: Int
        get() = _count
        set(value) {
            _count = value
            invalidateTextPaintAndMeasurements()
        }

    constructor(context: Context) : super(context) {
        init(null, 0)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(attrs, 0)
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        init(attrs, defStyle)
    }

    private fun init(attrs: AttributeSet?, defStyle: Int) {

        val a = context.obtainStyledAttributes(attrs, R.styleable.LinearView, defStyle, 0)

        _count = a.getInt(R.styleable.LinearView_count, 0)

        a.recycle()
        orientation = VERTICAL

        // Update TextPaint and text measurements from attributes
        invalidateTextPaintAndMeasurements()
    }

    private fun invalidateTextPaintAndMeasurements() {
        removeAllViews()
        (1..count).forEach { _ ->
            addView(TextView(context).apply {
                text = System.currentTimeMillis().toString()
                setPadding(33, 33, 33, 33)
            })
        }
    }

}